import axios from "axios";


// axios.defaults.headers['token'] = localGet('token') || ''

// 默认 post 请求，使用 application/json 形式
axios.defaults.headers.post['Content-Type'] = 'application/json'
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  config.headers['X-Token'] = getToken();
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 请求拦截器，内部根据返回值，重新组装，统一管理。
axios.interceptors.response.use(
  response => {
    // blob 直接返回文件流数据
    if (response.config.responseType === 'blob') {
      const fileName = decodeURI(
        // response.headers['content-disposition'] 默认获取不到，需要在 .Net Core Startup.cs 中进行配置
        response.headers['content-disposition'].split('filename*=UTF-8\'\'')[1]
      )
      return Promise.resolve({ data: response.data, fileName: fileName })
    }

    return response.data

    // ......
  },
  error => {
    if(error.response.status==401){
      sessionStorage.clear();
      alert("登录已过期，请重新登录")
      location.replace("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxaa3744f6b6f630f2&redirect_uri=http://hrms.ryderems.com/itsm.html&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect");

      //location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxaa3744f6b6f630f2&redirect_uri=http://hrms.ryderems.com/itsm.html&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect";
    }
    return Promise.reject(error)
  }
)
function getToken(){
  try {
    var token = sessionStorage.getItem('token');
    if(sessionStorage.getItem('RYD_UserId')!=null){
      token+=";"+sessionStorage.getItem('RYD_UserId')
    }
    return token;
  } catch (error) {
    return null;
  }
}
export default axios;